<template>
  <div class="member-address">
    <!-- 列表头部 -->
    <div class="header">
      <h4>收货地址<span style="font-size:14px">（最多可保存10条地址，还能保存<span>{{10 - addressList.length}}</span>条）</span></h4>
      <a href="javascript:;" @click="openAddressEdit({})" class="green">+新建地址</a>
    </div>
    <div v-if="loading" class="loading"></div>
    <div v-if="!loading && addressList.length === 0">
      <AddressNone />
    </div>
    <!-- 地址列表 -->
    <AddressItem
      v-for="item in addressList"
      :key="item.id" :addr="item"
      @on-delete="handlerDelete"
      @on-edit="openAddressEdit"
      @on-setDefault="setDefault"
    />
  </div>
  <!-- 新建地址的弹窗 -->
  <AddressEdit ref="addressEditCom" @on-success="successHandler" />
</template>

<script>
import AddressItem from './components/address-item.vue'
import AddressEdit from './components/address-edit.vue'
import AddressNone from './components/address-none.vue'
import { findAddressList, deleteAddress, setdefaultAddress } from '@/api/order'
import { onMounted, ref } from 'vue'
import Message from '@/components/library/message'
import Confirm from '@/components/library/confirm'
export default {
  name: 'AddressManagePage',
  components: {
    AddressItem,
    AddressEdit,
    AddressNone
  },
  setup () {
    const loading = ref(false)
    const addressList = ref([])
    const getAddressList = () => {
      loading.value = true
      findAddressList().then(data => {
        addressList.value = data.result
        // 1.遍历地址列表数据
        addressList.value.forEach(item => {
          // 2.如果地址列表中存在默认地址，就将默认地址显示为列表首位
          if (item.isDefault === 0) {
            addressList.value.reverse()
          }
        })
        loading.value = false
      })
    }
    // 组件挂载后执行获取地址列表数据函数
    onMounted(() => {
      getAddressList()
    })
    // 打开添加编辑收货地址组件
    const addressEditCom = ref(null)
    const openAddressEdit = (item) => {
      // 添加 {} 修改 {数据}
      addressEditCom.value.open(item)
    }
    const successHandler = (formData) => {
      // 根据formData中的ID去当前地址列表中查找，有就是修改，否则是添加
      const address = addressList.value.find(item => item.id === formData.id)
      if (address) {
        // 修改
        for (const key in address) {
          address[key] = formData[key]
        }
      } else {
        // 如果是添加：向list中追加一条
        // 当修改formData的时候，数组中数据也会更新，因为是同一个引用地址
        // 什么时间修改formData，当你打开对话框需要清空之前的输入信息
        // 克隆formData数据
        const jsonStr = JSON.stringify(formData)
        // eslint-disable-next-line vue/no-mutating-props
        addressList.value.unshift(JSON.parse(jsonStr))
        getAddressList()
      }
    }
    // 删除地址
    const handlerDelete = (addr) => {
      Confirm({ text: '亲，您确定要删除该地址吗？' }).then(() => {
        deleteAddress(addr.id).then(() => {
          Message({ type: 'success', text: '删除地址成功' })
          getAddressList()
        })
      }).catch(e => {})
    }
    // 设置默认收货地址
    const setDefault = (addr) => {
      setdefaultAddress(addr.id, 0).then(() => {
        Message({ type: 'success', text: '设置默认地址成功' })
        // 遍历地址列表
        addressList.value.forEach(item => {
          // 如果遍历的地址ID与选中的地址ID相等则选中地址设置为默认
          if (item.id === addr.id) {
            addr.isDefault = 0
          } else {
            addr.isDefault = 1
          }
          // 重新获取地址列表
          getAddressList()
        })
      })
    }
    return { loading, openAddressEdit, addressList, addressEditCom, handlerDelete, successHandler, setDefault }
  }
}
</script>

<style lang="less" scoped>
.member-address {
  height: 100%;
  background: #fff;
  padding: 0 20px;
  .loading {
    height: 100%;
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background: rgba(255,255,255,.9) url(../../../assets/images/loading.gif) no-repeat center;
  }
  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 20px 0 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    h4 {
      font-size: 18px;
      font-weight: normal;
    }
    .green {
      color: @xtxColor;
    }
  }
}
</style>
